import {selectPmFormUser} from '@/api/assessment'
import {useLoading} from '@/hooks/loading'
import useModal from '@/hooks/modalHook'
import {ant_design_vue} from '@/libs/global/antDesignVue'
import {defineComponent, reactive, computed, watch} from 'vue'
import {CnMediumSpan} from '../text'
const {message} = ant_design_vue

export namespace InitiationScore {
  export namespace Emits {
    export type ConfirmArg = {pmGroupList: string[]; pmGroupUserList: string[]}
    export type Confirm = (data: ConfirmArg) => true
  }
}

const InitiationScoreModal = defineComponent({
  props: {
    visible: Boolean,
    pmFormId: {
      type: Number,
      required: true
    }
  },
  emits: {
    'update:visible': (data: boolean): boolean => true,
    confirm: (data: InitiationScore.Emits.ConfirmArg): boolean => true
  },
  setup(props, {emit}) {
    const {visible, openModal, closeModal} = useModal()
    const {loading, startLoading, closeLoading} = useLoading()
    let state = reactive<{
      searchValue: string
      searchType: 'evalutaion' | 'employee'
      userAndEvaluationByPmForm: PmForm.UserAndEvaluationByPmForm
    }>({
      searchValue: '',
      searchType: 'evalutaion',
      userAndEvaluationByPmForm: {
        pmGroupList: [],
        pmGroupUserList: []
      }
    })

    let evalutaionState = reactive<{
      targetKeys: string[]
      selectedKeys: string[]
      dataSource: PmForm.PmGroup[]
    }>({
      targetKeys: [],
      selectedKeys: [],
      dataSource: []
    })

    let employeeState = reactive<{
      targetKeys: string[]
      selectedKeys: string[]
      dataSource: PmForm.PmGroupUser[]
    }>({
      targetKeys: [],
      selectedKeys: [],
      dataSource: []
    })

    const employeeTransferDataSource = computed<TransferDataSource[]>(() =>
      state.userAndEvaluationByPmForm.pmGroupUserList
        .map(item => ({
          key: item.pmGroupUserDDId + '',
          title: item.pmGroupUserName,
          description: '',
          disabled: false
        }))
        .filter(item => item.title.includes(state.searchValue || ''))
    )
    const evalutaionTransferDataSource = computed<TransferDataSource[]>(() =>
      state.userAndEvaluationByPmForm.pmGroupList
        .map(item => ({
          key: item.pmGroupId + '',
          title: item.pmGroupName,
          description: item.pmGroupDesc,
          disabled: false
        }))
        .filter(item => item.title.includes(state.searchValue || ''))
    )

    const transferDataSource = computed(() => {
      if (state.searchType === 'employee') {
        return employeeTransferDataSource.value
      } else {
        return evalutaionTransferDataSource.value
      }
    })

    watch(
      () => props.visible,
      n => {
        if (n) {
          startLoading()
          openModal()
          getModalData()
        } else {
          closeModal()
        }
      },
      {immediate: true}
    )

    watch(
      () => visible.value,
      n => {
        emit('update:visible', n)
        // 关闭后清空状态
        if (!n) {
          state.searchType = 'evalutaion'
          clearTransferStatus()
        }
      }
    )

    watch(
      () => state.searchType,
      n => {
        clearTransferStatus()
      }
    )

    function handleModalConfirm() {
      console.log(employeeState.targetKeys)
      console.log(evalutaionState.targetKeys)
      if (!employeeState.targetKeys.length && !evalutaionState.targetKeys.length) {
        message.warning('请先添加考评组或者考评人员')
        return
      }
      emit('confirm', {
        pmGroupUserList: employeeState.targetKeys,
        pmGroupList: evalutaionState.targetKeys
      })
      closeModal()
    }

    function clearTransferStatus() {
      evalutaionState.targetKeys = []
      evalutaionState.selectedKeys = []
      employeeState.targetKeys = []
      employeeState.selectedKeys = []
    }

    function getModalData() {
      startLoading()
      selectPmFormUser({pmFormId: props.pmFormId})
        .then(res => {
          evalutaionState.dataSource = res.data.pmGroupList
          employeeState.dataSource = res.data.pmGroupUserList
          state.userAndEvaluationByPmForm = res.data
          closeLoading()
        })
        .catch(err => {
          evalutaionState.dataSource = []
          employeeState.dataSource = []
          state.userAndEvaluationByPmForm = {
            pmGroupList: [],
            pmGroupUserList: []
          }
          closeLoading()
        })
    }

    return () => (
      <a-modal
        class='custom-modal w-1/3'
        title='发起评分'
        v-model={[visible.value, 'visible']}
        onOk={handleModalConfirm}
      >
        {loading.value ? (
          <div class='flex items-center justify-center py-12'>
            <a-spin spinning={true}></a-spin>
          </div>
        ) : (
          <div>
            <div class='h-48 border-1 border-cardLine flex items-center justify-between px-24'>
              <div class='flex items-center gap-x-32'>
                <CnMediumSpan
                  class={[
                    'cursor-pointer',
                    state.searchType === 'evalutaion' ? 'text-primary' : ''
                  ]}
                  onClick={() => {
                    state.searchType = 'evalutaion'
                  }}
                >
                  按考评组
                </CnMediumSpan>
                <CnMediumSpan
                  class={['cursor-pointer', state.searchType === 'employee' ? 'text-primary' : '']}
                  onClick={() => {
                    state.searchType = 'employee'
                  }}
                >
                  按单个员工
                </CnMediumSpan>
              </div>
              <a-input
                class='w-266 rounded-4'
                placeholder={state.searchType === 'employee' ? '搜索被考核人' : '搜索考评组'}
                v-slots={{
                  prefix: () => <i class='iconfont icon-fangdajing text-infoHalf text-13'></i>
                }}
                allowClear
                v-model={[state.searchValue, 'value']}
              ></a-input>
            </div>
            <div class='h-475 p-16'>
              {state.searchType === 'employee' ? (
                <div class='w-full h-full'>
                  <a-transfer
                    class='w-full h-full'
                    listStyle={{
                      flex: 1,
                      height: '100%'
                    }}
                    locale={{
                      itemUnit: '名',
                      itemsUnit: '名',
                      notFoundContent: '列表为空',
                      searchPlaceholder: '请输入搜索内容'
                    }}
                    titles={['待评分人员', '需要评分人员']}
                    v-models={[
                      [employeeState.selectedKeys, 'selectedKeys'],
                      [employeeState.targetKeys, 'targetKeys']
                    ]}
                    dataSource={employeeTransferDataSource.value}
                    // dataSource={employeeState.dataSource}
                    // render={(item: PmForm.PmGroupUser) => item.pmGroupUserName}
                    render={(item: {title: string}) => item.title}
                    // :disabled="disabled"
                    // @change="handleChange"
                    // @selectChange="handleSelectChange"
                    // @scroll="handleScroll"
                  />
                </div>
              ) : (
                <div class='w-full h-full'>
                  <a-transfer
                    class='w-full h-full'
                    listStyle={{
                      flex: 1,
                      height: '100%'
                    }}
                    locale={{
                      itemUnit: '个',
                      itemsUnit: '个',
                      notFoundContent: '列表为空',
                      searchPlaceholder: '请输入搜索内容'
                    }}
                    titles={['待评分考评组', '需要评分考评组']}
                    v-models={[
                      [evalutaionState.selectedKeys, 'selectedKeys'],
                      [evalutaionState.targetKeys, 'targetKeys']
                    ]}
                    dataSource={evalutaionTransferDataSource.value}
                    // dataSource={evalutaionState.dataSource}
                    render={(item: {title: string}) => item.title}
                    // :disabled="disabled"
                    // onChange={(nextTargetKeys: string[], direction: string, moveKeys: string[]) => {
                    //   console.log('targetKeys: ', nextTargetKeys)
                    //   console.log('direction: ', direction)
                    //   console.log('moveKeys: ', moveKeys)
                    // }}
                    // @selectChange="handleSelectChange"
                    // @scroll="handleScroll"
                  />
                </div>
              )}
            </div>
          </div>
        )}
      </a-modal>
    )
  }
})

export default InitiationScoreModal
